import { ref, reactive, readonly } from 'vue';
import { getImageCaptchaApi, loginApi, logoutApi } from '../apis/loginApi';
import { removeToken } from '../util/authToken';

const USER_INFO_KEY = 'userInfo';

export default function useLoginFun() {
  const mobilePassShowRef = ref(false);
  const captchaRef = ref(null);
  const captchaIdRef = ref(null);
  const loginSaveLoadingRef = ref(false);
  const loginRuleFormRef = ref();
  const loginRuleForm = reactive({
    userName: '',
    passWord: '',
    captcha: '',
    rememberPass: false,
  });
  const loginAlterRef = ref({
    title: '',
    type: 'success',
    show: false,
  });

  const loginSaveLoadingReadonly = readonly(loginSaveLoadingRef);
  const captchaReadonly = readonly(captchaRef);
  const loginAlterReadonly = readonly(loginAlterRef);

  // 设置提示文案
  const setLoginAlter = ({ title, type }) => {
    loginAlterRef.value.title = title;
    loginAlterRef.value.type = type;
    loginAlterRef.value.show = true;
  };

  // 获取验证码
  const getImageCaptcha = async () => {
    try {
      const { id, imageBase64 } = await getImageCaptchaApi();
      captchaRef.value = imageBase64;
      captchaIdRef.value = id;
    } catch (error) {
      console.log(error);
    }
  };

  // 确认校验
  const loginSubmitForm = (formEl, goHome, isMobile) => {
    if (!formEl) return;
    !isMobile ? validatePc(formEl, goHome) : validateMobile(formEl, goHome);
  };
  // 移动端校验
  const validateMobile = async (formEl,goHome) => {
    const bool = await formEl.validate();
    if (bool) {
      saveForm(goHome);
    }
  };
  // pc、客户端校验
  const validatePc = (formEl, goHome) => {
    formEl.validate((valid) => {
      if (valid) {
        saveForm(goHome);
      } else {
        console.log('error submit!');
      }
    });
  };

  // 确认提交
  const saveForm = async (goHome) => {
    try {
      loginSaveLoadingRef.value = true;
      const param = {
        userName: loginRuleForm.userName,
        passWord: loginRuleForm.passWord,
        captchaId: captchaIdRef.value,
        captcha: loginRuleForm.captcha,
        rememberPass: loginRuleForm.rememberPass,
      };
      const res = await loginApi(param);
      if (res.code === 200) {
        setUserInfo(res.data);
        setLoginAlter({ title: '登录成功', type: 'success' });
        setTimeout(() => {
          goHome();
          loginRuleFormRef.value.resetFields();
        }, 1200);
      } else {
        setLoginAlter({ title: res.msg || '登录失败！', type: 'error' });
        getImageCaptcha();
      }
    } finally {
      setTimeout(() => {
        loginSaveLoadingRef.value = false;
        loginAlterRef.value.show = false;
      }, 1200);
    }
  };

  // 退出
  const logout = async () => {
    await logoutApi();
    await removeUserInfo();
    removeToken();
  };

  // 获取用户信息
  const getUserInfo = () => {
    return localStorage.getItem(USER_INFO_KEY)
      ? JSON.parse(localStorage.getItem(USER_INFO_KEY))
      : null;
  };
  // 缓存用户信息
  const setUserInfo = (user) => {
    localStorage.setItem(USER_INFO_KEY, JSON.stringify(user));
  };

  const removeUserInfo = async () => {
    localStorage.removeItem(USER_INFO_KEY);
  };

  const validateUserName = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请输入用户名'));
    } else {
      callback();
    }
  };
  const validatePassWord = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请输入密码'));
    } else {
      callback();
    }
  };
  const validateCaptcha = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请输入验证码'));
    } else {
      callback();
    }
  };
  const loginRules = reactive({
    userName: [{ validator: validateUserName, trigger: 'blur' }],
    passWord: [{ validator: validatePassWord, trigger: 'blur' }],
    captcha: [{ validator: validateCaptcha, trigger: 'blur' }],
  });

  return {
    mobilePassShowRef,
    loginRuleFormRef,
    loginRuleForm,
    loginRules,
    loginSaveLoadingReadonly,
    captchaReadonly,
    loginAlterReadonly,
    getImageCaptcha,
    loginSubmitForm,
    getUserInfo,
    setUserInfo,
    logout,
  };
}
